package file

import (
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/model"
	"github.com/bgmp/service"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"net/http"
)

func DownloadFile(c *gin.Context) {
	i := c.Request.URL.Query().Get("Sid")
	sid, err := model.ParseSid(i)
	if err != nil || sid == 0 {
		handler.ReplyError(c, http.StatusBadRequest, "arg[Sid] is invalid")
		return
	}
	f := &model.File{}
	f.Sid = sid
	err = f.Get(config.DB)
	if err != nil {
		handler.ReplyError(c, http.StatusBadRequest, "file is not found")
		return
	}
	content, err := service.DownloadFile(f.Link)
	if err != nil {
		log.Error(err)
		handler.ReplyError(c, http.StatusInternalServerError, "failed to download file")
		return
	}

	c.Data(http.StatusOK, f.Type, content)
}
